package club.justwill.single.persistence.dao;

import club.justwill.single.persistence.jpo.User;
import club.justwill.single.persistence.support.BaseDao;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;

import java.util.List;
import javax.persistence.NoResultException;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;

/**
 * Created by xiangnan on 10/28/15.
 */
@Repository
@Scope(ConfigurableBeanFactory.SCOPE_SINGLETON)
public class UserDao extends BaseDao<User> {
	public User getById(long userId) {
		Query query = em.createNamedQuery("User.getById").setParameter("userId", userId);
		try {
			return (User) query.getSingleResult();
		} catch (NonUniqueResultException e) {
			return (User) query.getResultList().get(0);
		} catch (NoResultException e) {
			return null;
		}
	}

	public User getByUserName(String userName){
		Query query = em.createNamedQuery("User.getByUserAliasName").setParameter("aliasName", userName);
		try {
			return (User) query.getSingleResult();
		} catch (NonUniqueResultException e) {
			return (User) query.getResultList().get(0);
		} catch (NoResultException e) {
			return null;
		}
	}

	public User getByInvitationCode(String invitationCode){
		Query query = em.createNamedQuery("User.getByInvitationCode").setParameter("invitationCode", invitationCode);
		try {
			return (User) query.getSingleResult();
		} catch (NonUniqueResultException e){
			return (User) query.getResultList().get(0);
		} catch (NoResultException e) {
			return null;
		}
	}

	public List<User> searchCommercial(int index, int size) {
		Query query = em.createNamedQuery("User.getCommercial").setFirstResult(index).setMaxResults(size);
		return query.getResultList();
	}

	public List<User> searchUsers(int index, int size) {
		Query query = em.createNamedQuery("User.getUsers").setFirstResult(index).setMaxResults(size);
		return query.getResultList();
	}
}
